import React, { useState, useEffect } from 'react';
import { Table, Input, Select, Space, Button, Card, Layout, Typography, Modal, Form, message } from 'antd';
import { SearchOutlined, DeleteOutlined } from '@ant-design/icons';
import { useNavigate } from "react-router-dom"
import TextArea from "antd/es/input/TextArea";
import {api} from "./api/request"; // 假设这是您的后端请求封装

// 布局组件
const { Content } = Layout;
const { Title } = Typography;

// 状态选择的选项
const statusOptions = [
    { label: '上线', value: 1 },
    { label: '下线', value: 0 }
];

// BlogPage 主组件
const BlogPage = () => {
    const navigate = useNavigate(); // 初始化导航实例

    // --- 状态定义 ---
    const [formData, setFormData] = useState({
        pageNum: 1,
        pageSize: 10,
        isOnline: undefined,
        name: ''
    });
    const [tableData, setTableData] = useState([]);
    const [total, setTotal] = useState(0);
    const [loading, setLoading] = useState(false);
    const [isAddModalVisible, setIsAddModalVisible] = useState(false);
    const [articleForm] = Form.useForm();

    // 删除相关状态
    const [isDeleteModalVisible, setIsDeleteModalVisible] = useState(false);
    const [currentDeleteId, setCurrentDeleteId] = useState<number | null>(null);

    // ✅ 新增：修改状态相关状态
    const [isStatusModalVisible, setIsStatusModalVisible] = useState(false);
    const [currentStatusId, setCurrentStatusId] = useState<number | null>(null);
    const [statusForm] = Form.useForm(); // 用于状态修改弹窗的表单实例

    // 状态下拉选项
    const onlineOptions = [
        { label: '全部', value: undefined },
        { label: '已上线', value: 1 },
        { label: '未上线', value: 0 }
    ];

    // --- 业务逻辑函数 ---

    // 加载博客列表数据
    const fetchBlogList = async () => {
        setLoading(true);
        try {
            const response = await api.post( 'blogs/page', formData);
            // 假设后端返回的数据结构是 { data: { records: [...], total: N } }
            const { records, total } = response.data;
            setTableData(records);
            setTotal(total);
        } catch (error) {
            console.error('获取博客列表失败:', error);
            message.error('获取列表失败');
        } finally {
            setLoading(false);
        }
    };

    // ✅ 新增：显示修改状态弹窗，并设置初始状态
    const handleShowStatusModal = (record: { id: number; isOnline: number; }) => {
        setCurrentStatusId(record.id); // 存储当前 ID
        // 设置表单的初始值，方便用户直接看到当前状态
        statusForm.setFieldsValue({ status: record.isOnline });
        setIsStatusModalVisible(true); // 显示弹窗
    };

    // ✅ 新增：修改状态操作
    const handleUpdateStatus = async () => {
        if (!currentStatusId) return;

        try {
            const values = await statusForm.validateFields();
            const newStatus = values.status;

            // 🎯 调用后端接口：http://localhost:8080/blogs/update-status?id=xx&status=1or0
            const response = await api.get(`blogs/update-status?id=${currentStatusId}&status=${newStatus}`);

            // 假设后端成功返回 status: true 或者其他表示成功的标识
            if (response.data) {
                message.success('状态修改成功');
                setIsStatusModalVisible(false); // 关闭弹窗
                fetchBlogList(); // 刷新列表
            } else {
                message.error('状态修改失败');
            }
        } catch (error) {
            console.error('修改状态失败:', error);
            message.error('状态修改失败，请重试');
        }
    };

    // --- 现有函数 (省略未修改部分) ---

    // 初始加载和查询条件变化时重新加载
    useEffect(() => {
        fetchBlogList();
    }, [formData]);

    // 搜索框输入变化
    const handleSearchChange = (e: { target: { value: any; }; }) => {
        setFormData({ ...formData, name: e.target.value, pageNum: 1 });
    };

    // 状态选择变化
    const handleStatusChange = (value: any) => {
        setFormData({ ...formData, isOnline: value, pageNum: 1 });
    };

    // 分页变化
    const handleTableChange = (pagination: { current: any; pageSize: any; }) => {
        setFormData({
            ...formData,
            pageNum: pagination.current,
            pageSize: pagination.pageSize,
        });
    };

    // 查询按钮处理（重置为第 1 页，触发 useEffect）
    const handleQuery = () => {
        setFormData({ ...formData, pageNum: 1 });
        fetchBlogList();
    };

    // 打开新增弹窗
    const handleAdd = () => {
        setIsAddModalVisible(true);
        articleForm.resetFields();
    };

    // 提交新增表单
    const handleAddSubmit = async () => {
        try {
            const values = await articleForm.validateFields();
            await api.post('blogs/create-or-update', {
                ...values,
                id: null
            });
            setIsAddModalVisible(false);
            fetchBlogList();
            message.success('新增成功');
        } catch (error) {
            console.error('新增文章失败:', error);
            message.error('新增失败');
        }
    };

    // 显示删除确认弹窗
    const handleShowDeleteModal = (id: number) => {
        setCurrentDeleteId(id);
        setIsDeleteModalVisible(true);
    };

    // 关闭删除确认弹窗
    const handleCloseDeleteModal = () => {
        setIsDeleteModalVisible(false);
        setCurrentDeleteId(null);
    };

    // 确认删除操作
    const handleConfirmDelete = async () => {
        if (!currentDeleteId) return;
        try {
            const response = await api.get(`blogs/delete?id=${currentDeleteId}`);
            if (response.data) {
                message.success('删除成功');
                handleCloseDeleteModal();
                fetchBlogList();
            } else {
                message.error('删除失败');
                handleCloseDeleteModal();
            }
        } catch (error) {
            console.error('删除博客失败:', error);
            message.error('删除失败，请重试');
            handleCloseDeleteModal();
        }
    };

    // --- 表格列配置 ---
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 80,
        },
        {
            title: '博客名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '状态',
            dataIndex: 'isOnline',
            key: 'isOnline',
            render: (isOnline: any) => isOnline ? '已上线' : '未上线',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
        },
        {
            title: '操作',
            key: 'action',
            // record 结构需要包含 id 和 isOnline
            render: (_: any, record: { id: number; isOnline: number; }) => (
                <Space size="middle">
                    <Button type="link" size="small" onClick={() => navigate(`/article/detail/${record.id}`)}>
                        编辑
                    </Button>
                    <Button type="link" size="small" onClick={() => navigate(`/article/view/${record.id}`)}>
                        查看
                    </Button>
                    {/* ✅ 修改：绑定点击事件，打开修改状态弹窗 */}
                    <Button type="link" size="small" onClick={() => handleShowStatusModal(record)}>
                        修改状态
                    </Button>
                    <Button
                        type="link"
                        size="small"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => handleShowDeleteModal(record.id)}
                    >
                        删除
                    </Button>
                </Space>
            ),
        },
    ];

    // --- 渲染组件 ---
    return (
        <Layout style={{ minHeight: '100vh' }}>
            <Content style={{ padding: '0 50px' }}>
                <div style={{ margin: '16px 0' }}>
                    <Card>
                        <Title level={4}>博客列表查询</Title>
                        <Space style={{ marginBottom: 16 }}>
                            <Input
                                placeholder="输入博客名称搜索"
                                allowClear
                                style={{ width: 300 }}
                                value={formData.name}
                                onChange={handleSearchChange}
                                prefix={<SearchOutlined />}
                            />
                            <Select
                                placeholder="选择状态"
                                style={{ width: 150 }}
                                value={formData.isOnline}
                                onChange={handleStatusChange}
                                options={onlineOptions}
                            />
                        </Space>
                        <Button type="primary" onClick={handleQuery}>查询</Button>
                        <Button type="primary" onClick={handleAdd}>新增</Button>

                        <Table
                            columns={columns}
                            dataSource={tableData}
                            rowKey="id"
                            loading={loading}
                            pagination={{
                                current: formData.pageNum,
                                pageSize: formData.pageSize,
                                total: total,
                                showSizeChanger: true,
                                showQuickJumper: true,
                                showTotal: (total) => `共 ${total} 条数据`,
                            }}
                            // @ts-ignore
                            onChange={handleTableChange}
                        />
                    </Card>
                </div>

                {/* 新增文章弹窗 (保持不变) */}
                <Modal
                    title="新增文章"
                    open={isAddModalVisible}
                    onCancel={() => setIsAddModalVisible(false)}
                    footer={[
                        <Button key="cancel" onClick={() => setIsAddModalVisible(false)}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" onClick={handleAddSubmit}>
                            保存
                        </Button>,
                    ]}
                    destroyOnClose={true}
                    width={700}
                >
                    <Form
                        form={articleForm}
                        layout="vertical"
                        initialValues={{ title: '', author: '', content: '' }}
                    >
                        {/* 表单内容... */}
                        <Form.Item name="id" hidden initialValue={null}>
                            <Input />
                        </Form.Item>
                        <Form.Item name="title" label="文章标题" rules={[{ required: true, message: '请输入文章标题' }]}>
                            <Input placeholder="请输入文章标题" />
                        </Form.Item>
                        <Form.Item name="author" label="作者" rules={[{ required: true, message: '请输入作者' }]}>
                            <Input placeholder="请输入作者" />
                        </Form.Item>
                        <Form.Item name="content" label="文章内容" rules={[{ required: true, message: '请输入文章内容' }]}>
                            <TextArea rows={10} placeholder="请输入文章内容" />
                        </Form.Item>
                    </Form>
                </Modal>

                {/* 删除确认弹窗 (保持不变) */}
                <Modal
                    title="确认删除"
                    open={isDeleteModalVisible}
                    onCancel={handleCloseDeleteModal}
                    footer={[
                        <Button key="cancel" onClick={handleCloseDeleteModal}>
                            取消
                        </Button>,
                        <Button key="confirm" type="primary" danger onClick={handleConfirmDelete}>
                            确认删除
                        </Button>,
                    ]}
                    destroyOnClose={true}
                    maskClosable={false}
                >
                    <p>确定要删除该博客吗？删除后数据将无法恢复！</p>
                </Modal>

                {/* ✅ 新增：修改状态弹窗 */}
                <Modal
                    title={`修改博客状态 (ID: ${currentStatusId})`}
                    open={isStatusModalVisible}
                    onCancel={() => setIsStatusModalVisible(false)}
                    footer={[
                        <Button key="cancel" onClick={() => setIsStatusModalVisible(false)}>
                            取消
                        </Button>,
                        <Button key="confirm" type="primary" onClick={handleUpdateStatus}>
                            确认修改
                        </Button>,
                    ]}
                    destroyOnClose={true}
                >
                    <Form
                        form={statusForm}
                        layout="vertical"
                        // 由于初始值在 handleShowStatusModal 中设置，这里不需要 initialValues
                    >
                        <Form.Item
                            name="status"
                            label="选择新状态"
                            rules={[{ required: true, message: '请选择要修改的状态' }]}
                        >
                            <Select
                                placeholder="选择状态"
                                options={statusOptions}
                                style={{ width: '100%' }}
                            />
                        </Form.Item>
                    </Form>
                </Modal>
            </Content>
        </Layout>
    );
};

export default BlogPage;